Page({
  data: {
    books: [],
    filePath: "",
    keywords: "",
    history: wx.getStorageSync("history") || [],
  },
  // 1. 获取书单
  getData() {
    wx.showLoading({
      title: "正在加载中...",
      mask: true,
    });

    wx.request({
      url: "https://hmajax.itheima.net/api/books",
      method: "GET",
      data: {
        creator: "zhangsan",
      },
      header: {},
      success: (res) => {
        console.log(res);
        this.setData({
          books: res.data.data,
        });

        wx.showToast({
          title: "数据获取成功!",
          mask: true,
          duration: 6000,
          icon: "none",
        });
      },
      fail: () => {},
      complete: () => {
        wx.hideLoading();
      },
    });
  },
  setStorage() {
    // 存入一个数据
    wx.setStorageSync("author", "黑马程序员");
    // 存入复杂类型数据
    wx.setStorageSync("user", { name: "小明", age: 18 });
  },
  getStorage() {
    // 读取本地数据
    const author = wx.getStorageSync("author");
    console.log(author);
    const user = wx.getStorageSync("user");
    console.log(user);
  },
  removeStorage() {
    // 删除本地数据
    wx.removeStorageSync("logs");
  },
  clearStorage() {
    // 清空本地数据
    wx.clearStorageSync();
  },
  async chooseImage() {
    // 调用 API 获取图片
    const result = await wx.chooseMedia({
      count: 1,
      mediaType: ["image"],
      // success(result) {
      //   console.log(result);
      // }
    });

    // console.log(result);
    // 读取并渲染图片
    this.setData({
      filePath: result.tempFiles[0].tempFilePath,
    });
  },
  searchByKeywords() {
    const { history, keywords } = this.data;
    history.push(keywords);
    // 更新数据, 重新渲染页面
    this.setData({ history, keywords: "" });
    // 记录数到本地存储
    wx.setStorageSync("history", history);
  },
  clearHistory() {
    this.setData({ history: [] });
    wx.removeStorageSync("history");
  },
});
